// noinspection JSUnresolvedFunction

import {createRouter, createWebHistory} from 'vue-router'
import {useAccountStore} from "~/utils/store/account.js";
import {layout, login, route404} from "~/utils/router/routers.js";
import {CONFIG} from "~/utils/conf/index.js";
import {Cookies} from "quasar";

const ROUTE_ACCESS = 1

const asyncRouterMap = [
    layout,
    route404,
]

const router = createRouter({
    history: createWebHistory(), routes: [
        login,
    ],
})


const filterAsyncRouter = (routes) => {
    const account_store = useAccountStore()
    const perms = account_store.permissions

    return routes.filter((route) => {
        // 检查是否有子路由
        if (route.children && route.children.length > 0) {
            route.children = filterAsyncRouter(route.children)
        }
        // 检查是否有权限
        const perm_id = `${route.name}__route`
        if (perms.hasOwnProperty(perm_id) && perms[perm_id][route.name]['status'] === ROUTE_ACCESS) return true
        return CONFIG.WHITE_ROUTES.includes(route.name);
    })
}

// 检查用户是否已登录
const hasLogin = async () => {
    const refresh = Cookies.get('refresh')
    console.log('refresh', refresh)
    if (!refresh) return false
    const account_store = useAccountStore()
    console.log(!!account_store.userinfo)
    if (!account_store.userinfo) await account_store.refreshToken(refresh)
    return true
}

let has_add_router = false

router.beforeEach(async (to) => {
    const account_store = useAccountStore()
    // 登录页面直接跳转
    if (to.name === 'login') return true
    // 检查是否已登录, 未登录跳转到登录页面
    const has_login = await hasLogin()
    if (!has_login) return {name: 'login', query: {next: to.path}}
    // 已经添加路由,直接跳转
    if (!!account_store.has_add_router && has_add_router) return true
    // 没有添加路由,添加路由
    router.removeRoute('layout')
    const asyncRouter = filterAsyncRouter(asyncRouterMap)
    for (const route of asyncRouter) {
        router.addRoute(route)
    }
    // 根据路由生成菜单
    generateMenuList(layout.children)
    // 标记已经添加路由
    account_store.has_add_router = true // 用来标记是否登出,因为登出后删除了所有路由不会将has_add_router置为false,登录后不刷新页面不会加载新路由
    has_add_router = true
    return {...to, replace: true}
})

// 根据路由生成菜单
const generateMenuList = (routes) => {
    const account_store = useAccountStore()
    const perms = account_store.permissions
    const menu_list = []
    routes.forEach(route => {
        if (!!route.meta?.hide) return
        const perm_id = `${route.name}_route`
        if (perms.hasOwnProperty(perm_id) && perms[perm_id][route.name]['status'] === ROUTE_ACCESS || CONFIG.WHITE_ROUTES.includes(route.name)) {
            const menu = {
                label: route.meta?.label,
                icon: route.meta?.icon,
                nodeKey: 'name',
                name: route.name,
                handler: () => {
                    if (!!route.meta?.go || !route.children) router.push({name: route.name}).then()
                },
            }
            if (route.children && route.children.length > 0) menu['children'] = generateMenuList(route.children)
            menu_list.push(menu)
        }
    })
    account_store.menu_list = menu_list
    return menu_list
}

router.afterEach(() => {
})

export default router